package com.sqllog.admin.framework.config;

import org.apache.catalina.connector.Connector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class GracefulShutDown implements TomcatConnectorCustomizer, ApplicationListener<ContextClosedEvent> {

	private static final Logger logger = LoggerFactory.getLogger(GracefulShutDown.class);
	private volatile Connector connector;
	private final int waitTime = 1800;

	@Override
	public void customize(Connector connector) {
		this.connector = connector;
	}

	/**
	 * 关闭资源
	 */
	@Override
	public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
		// tomcat 暂停对外服务
		logger.info("暂停tomcat处理http请求...");
		this.connector.pause();
		logger.info("关闭容器资源...");
		// 获取tomcat 线程池
		Executor executor = this.connector.getProtocolHandler().getExecutor();
		try {
			if (executor instanceof ThreadPoolExecutor) {
				ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
				// 关闭tomcat 线程池
				threadPoolExecutor.shutdown();
				if (!threadPoolExecutor.awaitTermination(waitTime, TimeUnit.SECONDS)) {
					logger.warn("Tomcat 进程在 " + waitTime + " 秒内无法结束，尝试强制结束");
				}
			}
		} catch (Exception e) {
			logger.error("关闭资源异常 {}", e);
			Thread.currentThread().interrupt();
		}
	}
}
